package string

import (
	"bytes"
	"fmt"
)

// https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvaszc/
// 异位词分组
// 算法: 每个字符串都进行排序之后再比较
// 算法: 将每一个单词，每个字母的出现次数都记录在数组中，然后再每一个字母都进行比较
// 当前: TE
func groupAnagrams(strs []string) (retArr [][]string) {
	retArr = make([][]string, 0)
	occurMap := make(map[string][]string)
	for _, currentStr := range strs {
		currentOccur := newCharacterOccur(currentStr)
		mapMark := currentOccur.String()
		if nil != occurMap[mapMark] {
			occurMap[mapMark] = append(occurMap[mapMark], currentStr)
		} else {
			occurMap[mapMark] = make([]string, 0)
			occurMap[mapMark] = append(occurMap[mapMark], currentStr)
		}
	}

	for _, currentSlice := range occurMap {
		retArr = append(retArr, currentSlice)
	}
	return
}

type characterOccur struct {
	times []int
}

// TE，废弃这种标记方式
func (occur *characterOccur) equals(anoOccur *characterOccur) bool {
	for index := 0; index < len(occur.times); index++ {
		if occur.times[index] != anoOccur.times[index] {
			return false
		}
	}
	return true
}

func (occur *characterOccur) String() string {
	var buffer bytes.Buffer
	for index := 0; index < len(occur.times); index++ {
		buffer.WriteString(fmt.Sprintf("|%d", occur.times[index]))
	}
	return buffer.String()
}

func newCharacterOccur(str string) (ret *characterOccur) {
	ret = &characterOccur{times: make([]int, 26)}
	for _, currentChara := range str {
		ret.times[currentChara-'a']++
	}
	return
}
